<template>
  <MainSlot v-loading="loading">
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="search"
        @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm>
    </template>
    <!-- <template v-slot:tab>
        <EnumSlot @handleEvent="getEnumEvent" :selectIndex="selectIndex"></EnumSlot>
      </template> -->
    <!-- <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template> -->
    <template v-slot:table>
      <TableData :tableThead="tableThead" :dataList="dataList" :loading="loading" @selection-change="selectionChange">
        <template v-slot:inputPondDetailList="{ row }">
          <el-button type="text" @click="lookView(row.inputPondDetailList)">查看</el-button>
        </template>
        <template v-slot:batchStatus="{ row }">
          {{ row.batchStatus == 'SEALED_POND' || row.batchStatus == 'COMPLETED' ? '封塘' : '未封塘' }}
        </template>
      </TableData>
    </template>
    <template v-slot:pagination>
      <Pagination @size-Change="handleSizeChange" :size="size" @current-change="handleCurrentChange" :page="page"
        :total=total>
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <AddEdit :title="'批次'" @closeDialog="closeDialog" :addEditFlag="addEditFlag" :dialogVisible="dialogVisible"
        :data="formData">
      </AddEdit>
      <el-dialog :close-on-click-modal="false" title="投塘详情" :visible.sync="dialogVisible_lookview" width="60%"
        :before-close="() => {
          dialogVisible_lookview = false
        }">
        <el-table :data="tableList_lookView" border style="width: 100%">
          <el-table-column prop="plantVarietyName" label="品种" width="180">
          </el-table-column>
          <el-table-column prop="specificationName" label="规格" width="180">
          </el-table-column>
          <el-table-column prop="num" label="数量">
          </el-table-column>
          <el-table-column prop="weight" label="重量(斤)">
          </el-table-column>
        </el-table>
        <!-- tableList_lookView -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible_lookview = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible_lookview = false">确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components/MainSlot";
import Pagination from '@/components/Pagination';
import SearchForm from '@/components/SearchForm';
import TableData from '@/components/TableData';
import BtnSlot from '@/components/BtnSlot';
import EnumSlot from '@/components/EnumSlot';
import AddEdit from './components/addEdit.vue';
import pondInformationManagement from '@/api/pondManagment/pondInformationManagement.js';
import facilityManagement from '@/api/digtalOperation/facilityManagement';
import batch from '@/api/batch/batchManagement';
import varietyManagement from '@/api/basicInformation/varietyManagement.js';
import staffManage from '@/api/basicInformationOperate/staffManage';

export default {
  components: { MainSlot, Pagination, SearchForm, TableData, BtnSlot, EnumSlot, AddEdit },
  data() {
    return {
      unfoldFlag: false,
      loading: false,
      dialogVisible: false,
      dialogVisible_lookview: false,
      addEditFlag: 'add',
      selectList: [],
      formData: {},
      tableList_lookView: [],
      searchFormData: {},
      page: 1,
      size: 10,
      total: 10,
      selectIndex: 0,
      btnList: ['export'],
      dataList: [],
      varietyList: [],
      tableThead: [
        { isShow: true, label: '批次名称', prop: 'batchName', minWidth: '120px' },
        { isShow: true, label: '投塘设施', prop: 'facilityName' },
        { isShow: true, label: '投塘详情', slotName: 'inputPondDetailList' },
        { isShow: true, label: '操作人', prop: 'staffName' },
        { isShow: true, label: '是否封塘', slotName: 'batchStatus' },
        { isShow: true, label: '投塘日期', prop: 'inputDate' },
      ],
      personList: [],
      facilityList: [],
      formItemList: [
        {
          label: '养殖设施',
          type: 'select',
          selectOptions: [],
          param: 'facilityId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '选择批次',
          type: 'select',
          selectOptions: [],
          param: 'batchId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '选择品种',
          type: 'select',
          selectOptions: [],
          param: 'plantVarietyId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '操作人',
          type: 'select',
          selectOptions: [],
          param: 'staffName',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '投塘日期',
          type: 'datetimerange',
          param: 'dateTime',
          multiple: false,
          isShow: true
        },
      ],
    }
  },
  mounted() {
    this.queryPageByCondition();
    this.initData();
  },
  methods: {
    async initData() {
      // 获取批次列表 
      let { data: batchList } = await batch.queryByCondition({ batchType: 'BREEDING' })
      this.batchList = batchList || []
      //获取养殖设施；
      let { data: facilityList } = await facilityManagement.getFacilityListByConditionAll({
        breedType: sessionStorage.breedType
      });
      let { data: varietyList } = await varietyManagement.queryByCondition({})
      this.facilityList = facilityList || [];
      this.varietyList = varietyList || [];
      let { data: personList } = await staffManage.queryByCondition({ status: true })
      this.personList = personList.map(item => {
        return {
          staffId: item.person.personId,
          staffName: item.person.name,
          ...item
        }
      });

      this.setFormOptions();
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param == 'facilityId') {
          console.log(this.facilityList)
          let selectOptions = this.facilityList.map(data => {
            return {
              text: data.facilityName, value: data.facilityId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param == 'plantVarietyId') {
          let selectOptions = this.varietyList.map(data => {
            console.log(data.plantVarietyName)
            return {
              text: data.plantVarietyName, value: data.plantVarietyId
            }
          })
          item.defaultSelect = this.searchFormData[item.param]
          item.selectOptions = selectOptions;
        };
        if (item.param == 'batchId') {
          let selectOptions = this.batchList.map(data => {
            return {
              text: data.batchName, value: data.batchId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param == 'staffName') {
          let selectOptions = this.personList.map(data => {
            return {
              text: data.person.name, value: data.person.name
            }
          })
          item.defaultSelect = this.searchFormData[item.param]
          item.selectOptions = selectOptions;
        };
      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },
    delList(deleteList = [], key = 'checkStageId') {
      let list = []
      deleteList.forEach(item => {
        list.push(item[key])
      })
      console.log(list)
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await pondInformationManagement.delList(list);
        if (res.code == 1) {
          this.$message.success(res.msg || '删除成功');
          this.queryPageByCondition();
        } else {
          this.$message.warning(res.msg || '删除失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    lookView(list = []) {
      if (list.length == 0) {
        this.$message.warning('投塘记录被清空无法查看！')
        return
      }
      this.tableList_lookView = list;
      this.dialogVisible_lookview = true;
    },
    queryPageByCondition() {
      let params = {
        page: this.page,
        size: this.size,
        entity: {
          ...this.searchFormData,
        }
      }
      pondInformationManagement.queryPageByCondition(params).then(res => {
        if (res.code == 1) {
          this.dataList = res.data.content || [];
          this.total = res.data.totalElements;
          if (res.data.totalPages && this.page > res.data.totalPages) {
            this.page = res.data.totalPages;
            this.queryPageByCondition();
          }
        } else {
          this.$message.warning(res.msg || '分页查询失败')
        }
      }).catch(err => {
        console.log(err)
      })
    },
    search(data) {
      this.page = 1;
      let endData = null;
      let startData = null;
      if (data.dateTime && data.dateTime.length == 2) {
        startData = `${data.dateTime[0]} 00:00:00`;
        endData = `${data.dateTime[0]} 23:59:59`;
      }
      this.searchFormData = {
        ...this.searchFormData,
        ...data,
        endTime: endData,
        startTime: startData
      };
      this.queryPageByCondition();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryPageByCondition();
    },
    // 多选方法
    selectionChange(val) {
      this.selectList = val || []
    },
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag)
      if (flag == 'add') {
        this.dialogVisible = true
      } else if (flag == 'delete') {
        if (this.selectList.length > 0) {
          this.delList(this.selectList)
        } else {
          this.$message.warning('请先选择表单数据项后再删除！')
        }
      }
      this.addEditFlag = flag
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.queryPageByCondition();
    },
  }
};
</script>
<style lang="scss" scoped></style>